package com.tianhui.consignortwofei.mvp.ui.fragment.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;

import com.fgs.common.CommonResponse;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.PasswordEditText;
import com.fgs.common.widget.TextChange;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.interf.OnLoginFragmentSwitchListener;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.contract.LoginContract;
import com.tianhui.consignortwofei.mvp.model.AccountModel;
import com.tianhui.consignortwofei.mvp.model.enty.CaptchaInfo;
import com.tianhui.consignortwofei.mvp.model.enty.LoginInfo;
import com.tianhui.consignortwofei.mvp.presenter.LoginPresenter;
import com.tianhui.consignortwofei.mvp.ui.activity.LoginActivityNew;
import com.tianhui.consignortwofei.mvp.ui.activity.MainActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.OnlyLookQuotListTwoActivity;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.utils.Crypt;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xutil.security.Base64Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/4/11
 * @description
 **/
public class PasswordFragment extends BaseFragment<LoginContract.View, LoginContract.Presenter> implements LoginContract.View, OnLoginFragmentSwitchListener {

    @BindView(R.id.fragment_password_nameEditText)
    public ClearEditText nameEditText;
    @BindView(R.id.fragment_password_passwordEditText)
    public PasswordEditText passwordEditText;
    @BindView(R.id.fragment_password_loginButton)
    public Button loginButton;
    @BindView(R.id.fragment_password_checkBox)
    public CheckBox checkBox;
    private boolean isChecked = false;
    private boolean isRemember;

    public PasswordFragment() {
    }

    @Override
    protected boolean isNeedLazyLoad() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_password;
    }

    @Override
    protected LoginContract.View createView() {
        return this;
    }

    @Override
    protected LoginContract.Presenter createPresenter() {
        return new LoginPresenter(getContext());
    }

    @Override
    protected void init() {

        new TextChange.Builder()
                .addEditText(nameEditText, 1)
                .addEditText(passwordEditText, 6)
                .addListenView(loginButton)
                .build();

        String userName = SharedPreferenceManager.getInstance().getAccountNumber();

        if (!TextUtils.isEmpty(userName)) {
            nameEditText.setText(userName);
            nameEditText.setSelection(userName.length());
        }


        isRemember = SharedPreferenceManager.getInstance().getRememberPasswordState();
        showRememberState(isRemember);

        if (isRemember) {
            String password = SharedPreferenceManager.getInstance().getPassword();
//            if (!TextUtils.isEmpty(password)) {
//                password = Base64Utils.decode(password);
                passwordEditText.setText(password);
//            }
        }

    }

    private void showRememberState(boolean isChecked) {
        checkBox.setChecked(isChecked);
    }

    @OnClick(R.id.fragment_password_rememberPasswordLinearLayout)
    public void rememberPassword() {
        isRemember = !isRemember;
        showRememberState(isRemember);
        SharedPreferenceManager.getInstance().setRememberPasswordState(isRemember);
    }

    @Override
    public void result(LoginInfo info) {
        SharedPreferenceManager.getInstance().setToken(info.token);

        String name = nameEditText.getText().toString().trim();
        if ("18833838825".equals(name)){
            //报价列表
            Bundle bundle=new Bundle();
            bundle.putInt("lookType",2);
            openActivity(OnlyLookQuotListTwoActivity.class,bundle);
        }else {
            openActivity(MainActivity.class);
        }
        getActivity().finish();
    }

    @Override
    public void authCodeResult() {

    }

    @OnClick(R.id.fragment_password_loginButton)
    public void login() {

        hideKeyboard();

        String name = nameEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();
        String pass=passwordEditText.getText().toString().trim();
        if (isRemember) {
            SharedPreferenceManager.getInstance().setPassword(pass);
        } else {
            SharedPreferenceManager.getInstance().setPassword("");
        }

        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShortToast("请输入用户名");
            return;
        }
//        if (!CheckUtil.isMobileNO(name)) {
//            ToastUtil.showShortToast("请输入正确的手机号");
//            return;
//        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShortToast("请输入密码");
            return;
        }
        if (password.length() < 8) {
            ToastUtil.showShortToast("密码不能少于8位");
            return;
        }

//        if (!CheckUtil.isPasswordStrength(password)) {
//            ToastUtil.showShortToast("密码必须包含字母和数字");
//            return;
//        }

        if (!isChecked) {
            showToast("请先阅读并同意用户协议和隐私政策");
            return;
        }




        String password2="";//WVZoa3pmNXhuanhRK2ZidnhBbFFDUT09
        try {
            String  passNew = Crypt.encrypt(password, Crypt.KEY, Crypt.IV);
            password2  = Base64Utils.encode(passNew);

        } catch (Exception e) {
            e.printStackTrace();
        }

        password = password2;
//        password = Base64Utils.encode(password);//原只用base加密

        Map<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("type", "1,2");

        LoginGet(map,name);

//        hideKeyboard();
//        LoginActivityNew loginActivityNew = (LoginActivityNew) getActivity();
//        if (loginActivityNew != null) {
//            loginActivityNew.getYanZheng();
//        }
//        new AuthCode(getContext()).authCode(new AuthCode.OnAuthCodeCallback() {
//            @Override
//            public void onAuthCallback(CaptchaInfo info) {
//                if (info.ret == 0) {
//                    map.put("appid", info.captchaAppId + "");
//                    map.put("randstr", info.randstr);
//                    map.put("ticket", info.ticket);
//
//                    SharedPreferenceManager.getInstance().setAccountNumber(name);
//                    SharedPreferenceManager.getInstance().clearToken();
//                    requestLogin(map);
//                }
//            }
//        });

    }

    private void requestLogin(Map<String, String> map) {
        getPresenter().login(map, true);
    }

    private void LoginGet(Map<String, String> map,String name) {
        AccountModel mLoginModel = new AccountModel();
        mLoginModel.loginModelGet(getActivity(), map, true, bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                //这一步是必须的，判断view是否已经被销毁
                if (getView() != null) {
                    try {
                        if (commonResponse.getCode() == 20000) {
                            boolean data = (boolean)commonResponse.getData();
                            if (data){
                                requestLogin(map);
                            }else {
                                hideKeyboard();
                                LoginActivityNew loginActivityNew = (LoginActivityNew) getActivity();
                                if (loginActivityNew != null) {
                                    loginActivityNew.getYanZheng();
                                }
//                                new AuthCode(getContext()).authCode(new AuthCode.OnAuthCodeCallback() {
//                                    @Override
//                                    public void onAuthCallback(CaptchaInfo info) {
//                                        if (info.ret == 0) {
//                                            map.put("appid", info.captchaAppId + "");
//                                            map.put("randstr", info.randstr);
//                                            map.put("ticket", info.ticket);
//
//                                            SharedPreferenceManager.getInstance().setAccountNumber(name);
//                                            SharedPreferenceManager.getInstance().clearToken();
//                                            requestLogin(map);
//                                        }
//                                    }
//                                });
                            }

                        } else {
                            setMsg(commonResponse.getMsg());
                        }
                    }catch (Exception e){
                        hideKeyboard();
                        LoginActivityNew loginActivityNew = (LoginActivityNew) getActivity();
                        if (loginActivityNew != null) {
                            loginActivityNew.getYanZheng();
                        }
//                        new AuthCode(getContext()).authCode(new AuthCode.OnAuthCodeCallback() {
//                            @Override
//                            public void onAuthCallback(CaptchaInfo info) {
//                                if (info.ret == 0) {
//                                    map.put("appid", info.captchaAppId + "");
//                                    map.put("randstr", info.randstr);
//                                    map.put("ticket", info.ticket);
//
//                                    SharedPreferenceManager.getInstance().setAccountNumber(name);
//                                    SharedPreferenceManager.getInstance().clearToken();
//                                    requestLogin(map);
//                                }
//                            }
//                        });
                    }


                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                if (getView() != null) {
//                    getView().setMsg(ExceptionHandle.handleException(e).message);
                    setMsg(e.message);
                }
            }
        });
    }




    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_PHONE:
                String phone = event.getMessage();
                nameEditText.setText(phone);
                if (!TextUtils.isEmpty(phone)) {
                    nameEditText.setSelection(phone.length());
                }
                break;
        }
    }

    @Override
    public void onFragmentSwitch(String phone) {
        if (nameEditText != null) {
            nameEditText.setText(phone);
            if (!TextUtils.isEmpty(phone)) {
                nameEditText.setSelection(phone.length());
            }
        }
    }

    @Override
    public String getPhone() {
        if (nameEditText != null) {
            return nameEditText.getText().toString().trim();
        }
        return "";
    }

    @Override
    public void setIsChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }



    public void sendYanZheng(CaptchaInfo info) {
//                CaptchaInfo info = JsonUtil.fromJson(data, new TypeToken<CaptchaInfo>() {
//                }.getType());
                                if (info.ret == 0) {
                                    String name = nameEditText.getText().toString().trim();
                                    String password = passwordEditText.getText().toString().trim();
                                    Map<String, String> map = new HashMap<>();
                                    map.put("username", name);
                                    String password2="";//WVZoa3pmNXhuanhRK2ZidnhBbFFDUT09
                                    try {
                                        String  passNew = Crypt.encrypt(password, Crypt.KEY, Crypt.IV);
                                        password2  = Base64Utils.encode(passNew);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    password = password2;
                                    map.put("password", password);
                                    map.put("type", "1,2");
                                    map.put("appid", info.captchaAppId + "");
                                    map.put("randstr", info.randstr);
                                    map.put("ticket", info.ticket);

                                    SharedPreferenceManager.getInstance().setAccountNumber(name);
                                    SharedPreferenceManager.getInstance().clearToken();
                                    requestLogin(map);
                                }
    }



}
